import { apiGetPayOrder, getMemberAdd, apiOrderCreate } from '../../api/index'
let app = getApp()
let skuData
let page = {
  /**
   * 页面的初始数据
   */
  data: {
    orderNum: 1,
    address: {},
    selectpay: false,
    hasAddress: false,
    skuData: [],
    totoalPrice: 0,
    makeMoney: 0,
    shipping: [],
    express_free: 0
  },
  getDefAdd () {
    getMemberAdd().then(
      res => {
        for (let i = 0; i < res.data.data.length; i++) {
          if (res.data.data[i].is_default === 1) {
            this.setData({
              address: res.data.data[i]
            })
          }
        }
      }
    )
  },
  changeAdd (add) {
    if (add) {
      this.setData({
        address: add
      })
    } else {
      this.getDefAdd()
    }
  },
  // 获取地址
  getAddress () {
    wx.navigateTo({
      url: '../add-admin/add-admin?name=1'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(JSON.parse(options.data))
    skuData = JSON.parse(options.data)
    this.changeAdd()
    this.setData({
      isIphoneX: app.globalData.isIphoneX,
      skuData
    })
  },
  getPayOrder (sku) {
    let id = sku[0].sku_id
    let num = sku[0].num
    let data = id + ':' + num
    let cartId = []
    let cartStr
    for (let i = 0; i < sku.length; i++) {
      cartId.push(sku[i].cart_id)
      cartStr = cartId.join(',')
    }
    apiGetPayOrder({
      order_tag: 'buy_now' || 'cart',
      order_sku_list: data || '',
      cart_list: cartStr.toString() || ''
    }).then(
      res => {
        this.data.shipping = res.data.express_company_list
        this.data.express_free = this.data.shipping.length > 0 ? res.data.express_company_list[0].express_fee - 0 : 0
        this.setData({
          express_free: this.data.shipping.length ? (res.data.express_company_list[0].express_fee - 0).toFixed(2) : '0.00'
        })
      }
    )
  },
  calcMoney (skuData) {
    let totoalPrice = 0
    let goodsPrice = 0
    let makeMoney = 0
    let orderNum = 0
    skuData.forEach(item => {
      goodsPrice += ((item.num - 0) * (item.price - 0))
      // -优惠券 +运费 目前暂无
      totoalPrice = goodsPrice - 0 + (this.data.express_free - 0)
      makeMoney += (item.make_money - 0) * (item.num - 0)
      orderNum += item.num - 0
      item.make_money = (item.make_money - 0).toFixed(2)
    })
    this.setData({
      skuData,
      orderNum,
      totoalPrice: totoalPrice.toFixed(2),
      goodsPrice: goodsPrice.toFixed(2),
      makeMoney: makeMoney.toFixed(2)
    })
  },
  // 立刻购买
  toPayment () {
    if (this.data.address.consigner) {
      let skuList = ''
      let skuData = this.data.skuData
      skuData.forEach(item => {
        skuList += item.sku_id + ':' + item.num + ','
      })
      skuList = skuList.slice(0, -1)
      let params = {
        goods_sku_list: skuList,
        pay_type: 0,
        shipping_company_id: this.data.shipping[0].co_id ? this.data.shipping[0].co_id : 0,
        leavemessage: '',
        shipping_type: 1
      }
      let data = JSON.stringify(this.data.skuData)
      apiOrderCreate(params).then(res => {
        wx.redirectTo({
          url: `../payment/payment?out_trade_no=${res.data.out_trade_no}&id=${res.data.order_id}&data=${data}`
        })
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请选择收货地址',
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../add-admin/add-admin'
            })
          }
        }
      })
    }
  },
  discount (e) {
    const index = e.detail.index
    let data = this.data.skuData
    this.min_buy = this.data.skuData.min_buy > 0 ? (this.data.skuData.min_buy - 0) : 1
    if (data[index].num <= this.min_buy) {
      console.log(this.min_buy)
      wx.showToast({
        title: '不能再少了',
        icon: 'none'
      })
    } else {
      data[index].num--
      this.calcMoney(data)
    }
  },
  add (e) {
    const index = e.detail.index
    let data = this.data.skuData
    this.max_buy = data.max_buy > 0 ? (data.min_buy - 0) : data[index].stock
    if (data[index].num < this.max_buy) {
      data[index].num++
      this.calcMoney(data)
    } else {
      wx.showToast({
        title: '超出库存了',
        icon: 'none'
      })
    }
  },
  // 跳转到优惠券
  toCoupon () {
    wx.navigateTo({
      url: '../coupon/coupon'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    this.getPayOrder(this.data.skuData)
    this.calcMoney(this.data.skuData)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  }
}
Page(page)
